const express = require('express');
const db = require('../utils/db.js')
const router = express.Router()

/*
1.获取用户id
2.根据选择的堂食/外送/商城订单(一级类型) ${req.query.active}
3.二级类型(六种)展示的信息有区别，特别是待消费

/取消订单 和 /确认收货：改变状态，修改语句

*/
// var order = '`' + 'order' + '`';
var order = 'orderlist';
//获取用户id
router.get('/userid', (req, res) => {
  // console.log(req.query.phone);
  const idsql = `SELECT id FROM userinfo WHERE phone = '${req.query.phone}';`
  db.query(idsql, (err, data) => {
    if (err) {
      res.send({
        msg: err
      })
    } else {
      res.send({
        userid: data[0].id
      })
    }
  })
})
router.get('/list', (req, res) => {
  // console.log(req.query.userid);
  const typeidSql = `SELECT id FROM type WHERE typeName = '${req.query.active}';`
  var listData = [];
  var ids = [];
  var items = []; //存放每一条订单中的所有餐品
  var shopInfo = {}; //存放每一条订单中的门店信息
  var orderInfo = {}; //存放每一条订单中的订单详细信息
  db.query(typeidSql, (err, data) => {

    if (err == null) {

      let typeid = data[0].id;
      const orderSql =
        `SELECT feetotal,discount,o.id,d.name,orderTime time,o.status,price,o.total FROM ${order} o,dininghall d WHERE type_id=${typeid} and user_id=${req.query.userid} and o.shop_ID=d.id;`
      db.query(orderSql, (err2, data2) => {

        if (err == null) {
          for (d in data2) {
            listData.push(data2[d]);
            //data2[d].id为每一条订单id
            ids.push(data2[d].id);
          }
          //每条订单需要获取其下的餐品
          for (let i in ids) {
            let itemSql =
              `SELECT menu_id id,m.name,m.picture,m.price,om.helt peopleNum,om.count,m.fee,m.discount FROM ${order} o,ordermenu om,menu m WHERE o.id=${ids[i]} and o.id=om.order_id and om.menu_id=m.id;`
            db.query(itemSql, function(err3, data3) {

              if (err) {
                res.send({
                  msg: err2
                })

              } else {
                for (ii in data3) items.push(data3[ii]);
                listData[i].item = items;
                items = [];

                if (i == ids.length - 1) {
                  //再来联表查一下门店信息
                  for (let oi in ids) {
                    let ssql =
                      `SELECT d.name '门店名称',d.address '门店地址',d.phone '联系方式' FROM ${order} o,dininghall d WHERE o.id=${ids[oi]} and o.shop_ID=d.id;`
                    // console.log(ssql);
                    // console.log('data：', ssql);
                    db.query(ssql, (err4, data4) => {
                      if (err4) {
                        res.send({
                          msg: err2
                        })
                      } else {
                        shopInfo = data4;
                        listData[oi].shopinfo = shopInfo;
                        shopInfo = {}

                        if (oi == ids.length - 1) {
                          for (let oi2 in ids) {
                            let osql =
                              `SELECT score '积分',tableware '餐具数量',t.typeName '就餐方式',peopleNum '用餐人数',table_num '桌号',number '订单编号',orderTime '下单时间',paymethod '支付方式',contactPho '联系方式',remark '备注' FROM ${order} o,type t WHERE o.id=${ids[oi2]} and user_id=${req.query.userid} and t.id=o.type_id;`
                            db.query(osql, (err5, data5) => {
                              if (err5) {
                                res.send({
                                  msg: err2
                                })
                              } else {
                                orderInfo = data5;
                                listData[oi2].orderinfo = orderInfo;
                                orderInfo = {};
                                let shop = '就餐方式';
                                // console.log(listData[oi2].orderinfo[0][shop]);
                                if (listData[oi2].orderinfo[0][shop] == '商城订单') {
                                  let orderid = listData[oi2].id;
                                  let shopsql =
                                    `SELECT om.scoreshop_id id,ss.productName name,ss.scoreNum integral,ss.pic picture,ss.price,om.count,o.code,o.vaild,o.ercode1 FROM ${order} o,ordermenu om,scoreshop ss WHERE o.id=${orderid} and o.id=om.order_id and om.scoreshop_id=ss.id;`
                                  db.query(shopsql, (err6, data6) => {
                                    if (err6) {
                                      res.send({
                                        msg: err6
                                      })
                                    } else {
                                      items = data6;
                                      listData[oi2].item = items;
                                      items = [];
                                      if (oi2 == ids.length - 1) {
                                        res.send({
                                          listData,
                                          msg: '获取成功'
                                        })
                                        // console.log(listData);
                                      }
                                    }
                                  })
                                } else {
                                  if (oi2 == ids.length - 1) {

                                    res.send({
                                      listData,
                                      msg: '获取成功'
                                    })
                                  }
                                }



                              }
                            })
                          }
                        }

                      }
                    })


                  }


                }
              }
            })
          }

        } else {
          res.send({
            msg: err2
          })
        }
      })
    } else {
      res.send({
        msg: err
      })
    }
  })
})

//取消订单
router.post('/cancelList', (req, res) => {
  const sql = `UPDATE ${order} o set o.status='已取消' WHERE o.id=${req.body.orderid};`;
  db.query(sql, (err, data) => {
    if (err) {
      res.send({
        msg: err
      })
    } else {
      res.send({
        msg: '取消成功'
      })
    }
  })
})
//确认收货
router.post('/receiveList', (req, res) => {
  const sql = `UPDATE ${order} o set o.status='已完成' WHERE o.id=${req.body.orderid};`;
  db.query(sql, (err, data) => {
    if (err) {
      res.send({
        msg: err
      })
    } else {
      res.send({
        msg: '成功'
      })
    }
  })
})
//刷新订单
router.post('/refreshlList', (req, res) => {
  var os = req.body.os;
  console.log(os);
  var oslen = os.length - 1;
  //定时器 15分钟后改变状态，待支付->已取消，制作中->已完成（堂食）  || 配送中（外送），配送中->已完成
  //循环当前获取的订单，查看状态，状态为待支付，制作中，配送中则改变
  // console.log(os[oslen].id);

  for (let i = 0; i < os.length + 1; i++) {
    if (os[i].status == '待支付') {
      const sql = `UPDATE ${order} o set o.status='已取消' WHERE o.id=${os[i].id};`;
      db.query(sql, (err, data) => {
        if (err) {
          res.send({
            msg: err
          })
        } else {
          console.log(os[i].id + '改变了');

        }
      })
    } else if (os[i].status == '制作中' && os[i].type == '堂食') {
      const sql = `UPDATE ${order} o set o.status='已完成' WHERE o.id=${os[i].id};`;
      db.query(sql, (err, data) => {
        if (err) {
          res.send({
            msg: err
          })
        } else {
          console.log(os[i].id + '改变了');
        }
      })
    } else if (os[i].status == '制作中' && os[i].type == '外送') {
      const sql = `UPDATE ${order} o set o.status='配送中' WHERE o.id=${os[i].id};`;
      db.query(sql, (err, data) => {
        if (err) {
          res.send({
            msg: err
          })
        } else {
          console.log(os[i].id + '改变了');
        }
      })
    } else if (os[i].status == '配送中') {
      const sql = `UPDATE ${order} o set o.status='已完成' WHERE o.id=${os[i].id};`;
      db.query(sql, (err, data) => {
        if (err) {
          res.send({
            msg: err
          })
        } else {
          console.log(os[i].id + '改变了');
        }
      })
    } else {
      res.send({
        msg: '不用刷新'
      })
    }
  }


})
//立即支付
router.post('/paylist', (req, res) => {
  const sql = `UPDATE ${order} o set o.status='制作中' WHERE o.id=${req.body.orderid};`;
  db.query(sql, (err, data) => {
    if (err) {
      res.send({
        msg: err
      })
    } else {
      res.send({
        msg: '成功'
      })
    }
  })
})

module.exports = router;
